package com.business.base;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.business.form.po.FormBean;
import com.business.form.service.FormControlService;
import com.business.form.service.FormService;
import com.business.frame.service.FieldService;
import com.common.DateProcess;
import com.common.DecimalProcess;
import com.common.ErrorLog;
import com.common.RenderPage;
import com.common.StringProcess;

@Controller
@RequestMapping(value = "/base")
public class BaseController {

	@Autowired
	private BaseService baseService;
	
	@Autowired
	FormService formService;
	
	@Autowired
	FormControlService formControlService;
	
	@Autowired
	FieldService fieldService;
	
	@RequestMapping(params = "method=save", method = RequestMethod.POST)
	public void save(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String action=StringProcess.convertToString(request.getParameter("action"));
			String submitFormId=StringProcess.convertToString(request.getParameter("hidSubmitFormId"));
			
			//收集数据
			List<Map<String,Object>> listFormSave1=new ArrayList<Map<String, Object>>();
			List<Map<String,Object>> listFormSave2=new ArrayList<Map<String, Object>>();
			List<Map<String,Object>> listFormControl=new ArrayList<Map<String, Object>>();
			
			FormBean formBean=formService.getBeanByKeyId(submitFormId);
			if(formBean!=null)
			{
				String formData=formBean.getFormData();
				if(formData!=null && formData.length()>0)
				{
					Map<String,Object> formDataMap=JSON.parseObject(formData, new TypeReference<Map<String,Object>>(){});
					
					String pageClassifyCode=formBean.getPageClassifyCode();
					if(pageClassifyCode.equals("bdy"))
					{
						listFormControl=(List<Map<String,Object>>)formDataMap.get("FormControl");
						if(formDataMap.get("FormSave")!=null)
						{
							List<Map<String,Object>> listFormSave=(List<Map<String,Object>>)formDataMap.get("FormSave");
							for(int i=0;i<listFormSave.size();i++)
							{
								if(StringProcess.convertToString(listFormSave.get(i).get("SaveType")).equals("1"))
								{
									listFormSave1.add(listFormSave.get(i));
								}
								else if(StringProcess.convertToString(listFormSave.get(i).get("SaveType")).equals("2"))
								{
									listFormSave2.add(listFormSave.get(i));
								}
							}
						}
					}
				}
			}
			
			StringBuilder sql;
			if(action.equals("insert"))
			{
				
				for(int i=0;i<listFormSave1.size();i++)
				{					
					String tableName=StringProcess.convertToString(listFormSave1.get(i).get("SaveTableName"));
					
					sql=new StringBuilder();
					Map<String, Object> item = new HashMap<String, Object>();
					sql.append("INSERT INTO "+tableName+" ");
					if(listFormSave2.size()>0)
					{
						sql.append("(");
						boolean isFirst=true;
						for(int j=0;j<listFormSave2.size();j++)
						{
							if(tableName.equals(listFormSave2.get(j).get("SaveTableName")))
							{
								if(!isFirst)
								{
									sql.append(",");
								}
								
								String saveFieldName=StringProcess.convertToString(listFormSave2.get(j).get("SaveFieldName"));
								sql.append(saveFieldName);
								isFirst=false;
							}
						}
						sql.append(") VALUES (");
						
						isFirst=true;
						for(int j=0;j<listFormSave2.size();j++)
						{
							if(tableName.equals(listFormSave2.get(j).get("SaveTableName")))
							{
								if(!isFirst)
								{
									sql.append(",");
								}
								
								String formControlId=StringProcess.convertToString(listFormSave2.get(j).get("FormControlId"));
								String saveFieldName=StringProcess.convertToString(listFormSave2.get(j).get("SaveFieldName"));
								String saveFieldValue=getSaveFieldValue(request,formControlId,listFormControl);
								sql.append("#{"+saveFieldName+"}");
								isFirst=false;
								
								item.put(saveFieldName, saveFieldValue);
							}
						}
						
						sql.append(")");
						
					}
					else
					{
						//没有设置保存字段！
					}
					
					
					item.put("insertSql", sql);
					baseService.insertBusiness(item);
					
				}
				
			}
			else if (action.equals("update"))
			{
				for(int i=0;i<listFormSave1.size();i++)
				{	
					String tableName=StringProcess.convertToString(listFormSave1.get(i).get("SaveTableName"));
					String keyFieldName="";
					List<String> keyFieldNames=fieldService.getTableKeyField(tableName);
					if(keyFieldNames.size()>0)
					{
						keyFieldName=keyFieldNames.get(0);
					}
					String keyFieldValue="";
					
					
					sql=new StringBuilder();
					Map<String, Object> item = new HashMap<String, Object>();
					sql.append("UPDATE "+tableName+" ");
					if(listFormSave2.size()>0)
					{
						boolean isFirst=true;
						for(int j=0;j<listFormSave2.size();j++)
						{
							if(tableName.equals(listFormSave2.get(j).get("SaveTableName")))
							{
								String saveFieldName=StringProcess.convertToString(listFormSave2.get(j).get("SaveFieldName"));
								String formControlId=StringProcess.convertToString(listFormSave2.get(j).get("FormControlId"));
								
								if(saveFieldName.equals(keyFieldName))
								{
									//主键字段不处理
									
									keyFieldValue=getSaveFieldValue(request,formControlId,listFormControl);
									continue;
								}
								
								if(isFirst)
								{
									sql.append("SET ");
								}
								else
								{
									sql.append(",");
								}
								
								sql.append(saveFieldName);
								sql.append("=");
								String saveFieldValue=getSaveFieldValue(request,formControlId,listFormControl);
								sql.append("#{"+saveFieldName+"}");
								isFirst=false;
								
								item.put(saveFieldName, saveFieldValue);
							}
						}
					}
					else
					{
						//没有设置保存字段！
					}
					
					sql.append(" WHERE "+keyFieldName+" = #{"+keyFieldName+"}");
					item.put(keyFieldName, keyFieldValue);
					
					item.put("updateSql", sql);
					baseService.updateBusiness(item);
				}
			}
			
			RenderPage.JsonByString(response, "1");
		}
		catch(Exception e)
		{
			ErrorLog.OnWrite(e);
		}
	}
	
	@RequestMapping(params = "method=delete", method = RequestMethod.POST)
	public void del(HttpServletRequest request, HttpServletResponse response) {
		try{
			
			List<Map<String,Object>> listFormRead1=new ArrayList<Map<String, Object>>();
			
			String listFormId=StringProcess.convertToString(request.getParameter("hidListFormId"));
			FormBean formBean=formService.getBeanByKeyId(listFormId);
			if(formBean!=null)
			{
				String formData=formBean.getFormData();
				if(formData!=null && formData.length()>0)
				{
					Map<String,Object> formDataMap=JSON.parseObject(formData, new TypeReference<Map<String,Object>>(){});
					
					String pageClassifyCode=formBean.getPageClassifyCode();
					if(pageClassifyCode.equals("lby"))
					{
						if(formDataMap.get("FormRead")!=null)
						{
							List<Map<String,Object>> listFormRead=(List<Map<String,Object>>)formDataMap.get("FormRead");
							for(int i=0;i<listFormRead.size();i++)
							{
								if(StringProcess.convertToString(listFormRead.get(i).get("ReadType")).equals("1"))
								{
									listFormRead1.add(listFormRead.get(i));
								}
							}
						}
					}
				}
			}
			
			String[] array = StringProcess.getRequest(request.getParameter("selectitem"), "").split(",");
			for (String itemId : array) {
				if(itemId.length()>0){
					
					for(int i=0;i<listFormRead1.size();i++)
					{	
						String tableName=StringProcess.convertToString(listFormRead1.get(i).get("ReadTableName"));
						String keyFieldName=StringProcess.convertToString(listFormRead1.get(i).get("KeyFieldName"));
						
						StringBuilder sql=new StringBuilder();
						sql.append("DELETE FROM "+tableName+" WHERE "+keyFieldName+" = #{"+keyFieldName+"}");
						
						Map<String, Object> item = new HashMap<String, Object>();
						item.put("deleteSql", sql);
						item.put(keyFieldName, itemId);
						baseService.deleteBusiness(item);
					}
					
				}
			}
			
			RenderPage.JsonByString(response, "1");
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
		
	}
	
	@RequestMapping("/query")
	public void query(Integer pageIndex, Integer pageSize, HttpServletRequest request, HttpServletResponse response,
			ModelMap map)
	{
		try{
			String listFormId=StringProcess.convertToString(request.getParameter("hidListFormId"));
			
			List<Map<String,Object>> listFormRead1=new ArrayList<Map<String, Object>>();
			List<Map<String,Object>> listFormFilter=new ArrayList<Map<String, Object>>();
			
			//Map<String, Object> search = new HashMap<String, Object>();
			//筛选条件
			
			FormBean formBean=formService.getBeanByKeyId(listFormId);
			if(formBean!=null)
			{
				String formData=formBean.getFormData();
				if(formData!=null && formData.length()>0)
				{
					Map<String,Object> formDataMap=JSON.parseObject(formData, new TypeReference<Map<String,Object>>(){});
					
					String pageClassifyCode=formBean.getPageClassifyCode();
					if(pageClassifyCode.equals("lby"))
					{
						if(formDataMap.get("FormRead")!=null)
						{
							List<Map<String,Object>> listFormSave=(List<Map<String,Object>>)formDataMap.get("FormRead");
							for(int i=0;i<listFormSave.size();i++)
							{
								if(StringProcess.convertToString(listFormSave.get(i).get("ReadType")).equals("1"))
								{
									listFormRead1.add(listFormSave.get(i));
								}
							}
						}
						if(formDataMap.get("FormFilter")!=null)
						{
							listFormFilter=(List<Map<String,Object>>)formDataMap.get("FormFilter");
						}
					}
				}
			}
			
			
			Map<String, Object> item = new HashMap<String, Object>();
			
			String sQLShowField="";
			String sQLFromTable="";
			String sQLWhereField="";
			String sQLOrderField="";
			String sQLGroupField="";
			if(listFormRead1.size()>0)
			{
				Map<String,Object> itemFormRead1=listFormRead1.get(0);
				
				sQLShowField=StringProcess.convertToString(itemFormRead1.get("SQLShowField"));
				sQLFromTable=StringProcess.convertToString(itemFormRead1.get("SQLFromTable"));
				sQLWhereField=StringProcess.convertToString(itemFormRead1.get("SQLWhereField"));
				sQLOrderField=StringProcess.convertToString(itemFormRead1.get("SQLOrderField"));
				sQLGroupField=StringProcess.convertToString(itemFormRead1.get("SQLGroupField"));
			}

			String sql="SELECT "+sQLShowField+" from "+sQLFromTable;
			boolean isWhere=false;
			if(sQLWhereField.length()>0)
			{
				sql=sql+" WHERE "+sQLWhereField;
				isWhere=true;
			}
			
			//过滤条件
			StringBuilder sqlWhere=new StringBuilder();
			for(int i=0;i<listFormFilter.size();i++)
			{
				String formFilterId=StringProcess.convertToString(listFormFilter.get(i).get("FormFilterId"));
				String filterTableName=StringProcess.convertToString(listFormFilter.get(i).get("FilterTableName"));
				String filterFieldName=StringProcess.convertToString(listFormFilter.get(i).get("FilterFieldName"));
				String formControlType=StringProcess.convertToString(listFormFilter.get(i).get("FormControlType"));
				String expression=StringProcess.convertToString(listFormFilter.get(i).get("Expression"));
				
				String preName="e"+formControlType+"_";
				String controlName=preName+formFilterId;
				String requestValue=StringProcess.convertToString(request.getParameter(controlName));
				if(requestValue.length()>0)
				{
					sqlWhere.append(" AND "+filterTableName+"."+filterFieldName);
					String likeString="";
					if(expression.equals("1"))
					{
						sqlWhere.append(" = ");
					}
					else if(expression.equals("2"))
					{
						sqlWhere.append(" LIKE ");
						likeString="%";
					}						

					sqlWhere.append("#{"+filterFieldName+"}");
					
					item.put(filterFieldName, likeString+requestValue+likeString);
				}
			}
			if(!isWhere && sqlWhere.length()>0)
			{
				sqlWhere.replace(1, 4, "WHERE");
			}
			sql=sql+sqlWhere.toString();
			
			if(sQLOrderField.length()>0)
			{
				sql=sql+" ORDER BY "+sQLOrderField;
			}
			if(sQLGroupField.length()>0)
			{
				sql=sql+" GROUP BY "+sQLGroupField;
			}
			
			item.put("selectSql", sql);
			Pager<Map<String, Object>> result=baseService.selectBusiness(item,pageIndex,pageSize);
			
			RenderPage.JsonByObject(response, result);
			
		}catch(Exception e){
			ErrorLog.OnWrite(e);
		}
	}
	
	@RequestMapping("/initFormControlValue")
	public void initFormControlValue(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			String submitFormId=StringProcess.convertToString(request.getParameter("submitFormId"));
			String keyId=StringProcess.convertToString(request.getParameter("keyId"));
			
			List<Map<String,Object>> list=new ArrayList<Map<String, Object>>(); 
			
			FormBean formBean=formService.getBeanByKeyId(submitFormId);
			if(formBean!=null)
			{
				String formData=formBean.getFormData();
				if(formData!=null && formData.length()>0)
				{
					Map<String,Object> formDataMap=JSON.parseObject(formData, new TypeReference<Map<String,Object>>(){});
				
					List<Map<String,Object>> listFormSave=(List<Map<String,Object>>)formDataMap.get("FormSave");
					List<Map<String,Object>> listFormSave1=new ArrayList<Map<String, Object>>();
					for(int i=0;i<listFormSave.size();i++)
					{
						if(StringProcess.convertToString(listFormSave.get(i).get("SaveType")).equals("1"))
						{
							listFormSave1.add(listFormSave.get(i));
						}
					}
					List<Map<String,Object>> listFormSave2=formControlService.selectSaveByFormId(submitFormId);
					
					list=returnResult(listFormSave1,listFormSave2,keyId);
				}
			}
			
			/*
			Map<String,Object> item=new HashMap<String, Object>();
			item.put("key", "e11_201712131859567122d495f20949d1a23a1d8d1499e159");
			item.put("value", "123");
			list.add(item);
			*/
			
			RenderPage.JsonByObject(response, list);
		}
		catch(Exception e){
			ErrorLog.OnWrite(e);
		}
	}
	
	@RequestMapping("/initInsertValue")
	public void initInsertValue(HttpServletRequest request, HttpServletResponse response)
	{
		try 
		{
			String ret="";
			
			String initValue=StringProcess.convertToString(request.getParameter("initValue"));
			
			if(initValue.equals("GUID"))
			{
				ret=StringProcess.getUUID();
			}
			
			RenderPage.JsonByString(response, ret);
		} 
		catch (Exception e) {
			ErrorLog.OnWrite(e);
		}
	}
	
	private List<Map<String,Object>> returnResult(List<Map<String,Object>> listFormSave1,List<Map<String,Object>> listFormSave2,String keyId)
	{
		List<Map<String,Object>> list=new ArrayList<Map<String, Object>>();
		Map<String,Object> item;
		
		for(Map<String,Object> itemFormSave1:listFormSave1)
		{
			String saveTableName=StringProcess.convertToString(itemFormSave1.get("SaveTableName"));

			for(Map<String,Object> itemFormSave2:listFormSave2)
			{
				if(StringProcess.convertToString(itemFormSave2.get("SaveTableName")).equals(saveTableName))
				{
					String saveFieldName=StringProcess.convertToString(itemFormSave2.get("SaveFieldName"));
					String formControlId=StringProcess.convertToString(itemFormSave2.get("FormControlId"));
					String formControlType=StringProcess.convertToString(itemFormSave2.get("FormControlType"));
					
					item=new HashMap<String, Object>();
					item.put("tableName", saveTableName);
					item.put("fieldName", saveFieldName);
					item.put("key", "e"+formControlType+"_"+formControlId);
					list.add(item);
				}
			}
		}
		
		for(Map<String,Object> itemFormSave1:listFormSave1)
		{
			String saveTableName=StringProcess.convertToString(itemFormSave1.get("SaveTableName"));
			List<String> listKeyField=fieldService.getTableKeyField(saveTableName);
			String keyFieldName="";
			if(listKeyField.size()>0)
			{
				keyFieldName=listKeyField.get(0);
			
				String sql="SELECT * FROM "+saveTableName+" WHERE "+keyFieldName+"='"+keyId+"'";
				
				Map<String, Object> itemSql = new HashMap<String, Object>();
				itemSql.put("selectSql", sql);
				List<Map<String, Object>> result=baseService.selectBusiness(itemSql);
				if(result.size()>0)
				{
					//有数据
					for(int i=0;i<list.size();i++)
					{
						item=list.get(i);
						if(StringProcess.convertToString(item.get("tableName")).equals(saveTableName))
						{
							String saveFieldName=StringProcess.convertToString(item.get("fieldName"));
							String value=StringProcess.encode(StringProcess.convertToString(result.get(0).get(saveFieldName)));
							item.put("value", value);
						}
					}
				}
			}
		}
		
		List<Map<String,Object>> newList=new ArrayList<Map<String, Object>>();
		for(Map<String,Object> item2:list)
		{
			String key=StringProcess.convertToString(item2.get("key"));
			Object value=item2.get("value");
			
			boolean isExist=false;
			for(Map<String,Object> newItem : newList)
			{
				if(value.equals(newItem.get("value")))
				{
					isExist=true;
					break;
				}
			}
			if(!isExist)
			{
				Map<String,Object> newItem=new HashMap<String, Object>();
				newItem.put("key", key);
				newItem.put("value", value);
				newList.add(newItem);
			}
		}
		
		return newList;
	}
	
	private String getSaveFieldValue(HttpServletRequest request,String formControlId,List<Map<String,Object>> listFormControl)
	{
		String ret="";
		
		//String formControlId=StringProcess.convertToString(itemFormSave.get("FormControlId"));
		
		for(int i=0;i<listFormControl.size();i++)
		{
			if(formControlId.equals(listFormControl.get(i).get("FormControlId")))
			{
				String formControlType=StringProcess.convertToString(listFormControl.get(i).get("FormControlType"));
				String formElementId="e"+formControlType+"_"+formControlId;
				ret=request.getParameter(formElementId);
				if(ret==null)
				{
					ErrorLog.OnWrite("表单找不到"+formElementId+"的元素！");
					ret="";
				}
			}
		}
		
		return ret;
	}
	
	@RequestMapping(params = "method=processOrder", method = RequestMethod.POST)
	public void processOrder(HttpServletRequest request, HttpServletResponse response, String action)
	{
		String keyId = StringProcess.getRequest(request.getParameter("keyId"), "");
		String refKeyId = StringProcess.getRequest(request.getParameter("refKeyId"), "");
		String value = StringProcess.getRequest(request.getParameter("value"), "");
		String refValue = StringProcess.getRequest(request.getParameter("refValue"), "");
		
		String dbName = StringProcess.getRequest(request.getParameter("dbName"), "");
		String tableName = StringProcess.getRequest(request.getParameter("tableName"), "");
		String keyFieldName = StringProcess.getRequest(request.getParameter("keyFieldName"), "");
		String sortFieldName = StringProcess.getRequest(request.getParameter("sortFieldName"), "");
		
		try
		{		
			if(value.equals(refValue))
			{
				Map<String, Object> result = new HashMap<String, Object>();
				result.put("result", "0");
				result.put("message", "移动的排序号不可以相同！");
				RenderPage.JsonByObject(response, result);
			}
			else
			{
				if(keyId.length()>0 && value.length()>0 && refKeyId.length()>0 && refValue.length()>0)
				{
					Map<String, Object> item1 = new HashMap<String, Object>();
					String updateSql = "UPDATE "+tableName+" SET "+sortFieldName+"="+refValue+" where "+keyFieldName+"='"+keyId+"'";
					item1 = new HashMap<String, Object>();
					item1.put("updateSql", updateSql);
					
					Map<String, Object> item2 = new HashMap<String, Object>();
					updateSql = "UPDATE "+tableName+" SET "+sortFieldName+"="+value+" where "+keyFieldName+"='"+refKeyId+"'";
					item2 = new HashMap<String, Object>();
					item2.put("updateSql", updateSql);
					
					if(dbName.equals("formDb"))
					{
						baseService.processOrderForm(item1,item2);
					}
					else if(dbName.equals("frameDb"))
					{
						baseService.processOrderFrame(item1,item2);
					}
					else
					{
						baseService.processOrderBusiness(item1,item2);
					}
				}
				
				//baseService.processOrder(action,keyId,refKeyId,value,refValue,dbName, tableName, keyFieldName, sortFieldName);
				
				Map<String, Object> result = new HashMap<String, Object>();
				result.put("result", "1");
				result.put("message", "");
				RenderPage.JsonByObject(response, result);
			}
			
		}
		catch(Exception e)
		{
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("result", "0");
			result.put("message", e.getMessage());
			RenderPage.JsonByObject(response, result);
			
			ErrorLog.OnWrite(e);
		}
		
	}
	
	public static Map<String, Object> AddChangeRow(Object invokeClass,List<Map<String, Object>> list,Map<String, Object> item,long totalCount,Integer pageIndex,int currentPageIndex,int pageCount,Integer pageSize,int currentPageCount,String keyFieldName,String sortFieldName,Map<String, Object> search)
	{
		try
		{
			//上移下移
			String pKeyId="";
			String nKeyId="";
			String pValue = "";
			String nValue = "";
			if(currentPageIndex==0 && pageIndex==1)
			{
				//不处理pValue
				if(totalCount!=1)
				{
					nKeyId=StringProcess.convertToString(list.get(currentPageIndex+1).get(keyFieldName));
					nValue=StringProcess.convertToString(list.get(currentPageIndex+1).get(sortFieldName));
				}
			}
			else if (currentPageIndex==currentPageCount-1 && pageIndex==pageCount)
			{
				//不处理nValue
				if(totalCount!=1)
				{
					pKeyId=StringProcess.convertToString(list.get(currentPageIndex-1).get(keyFieldName));
					pValue=StringProcess.convertToString(list.get(currentPageIndex-1).get(sortFieldName));
				}
			}
			else
			{
				Method m = invokeClass.getClass().getDeclaredMethod("selectPage",int.class,int.class, Map.class);
				
				if(currentPageIndex==0)
				{
					//Pager<Map<String, Object>> pResult = inter.getSelectPage(pageIndex-1,pageSize,search);
					Pager<Map<String, Object>> pResult =(Pager<Map<String, Object>>)m.invoke(invokeClass,pageIndex-1,pageSize,search);
					
					int pResultCount = pResult.getList().size();
					pKeyId = StringProcess.convertToString(pResult.getList().get(pResultCount-1).get(keyFieldName));
					pValue = StringProcess.convertToString(pResult.getList().get(pResultCount-1).get(sortFieldName));
					
					nKeyId=StringProcess.convertToString(list.get(currentPageIndex+1).get(keyFieldName));
					nValue=StringProcess.convertToString(list.get(currentPageIndex+1).get(sortFieldName));
				}
				if(currentPageIndex==currentPageCount-1)
				{
					pKeyId=StringProcess.convertToString(list.get(currentPageIndex-1).get(keyFieldName));
					pValue=StringProcess.convertToString(list.get(currentPageIndex-1).get(sortFieldName));
				
					//Pager<Map<String, Object>> nResult = inter.getSelectPage(pageIndex+1,pageSize,search);
					Pager<Map<String, Object>> nResult =(Pager<Map<String, Object>>)m.invoke(invokeClass,pageIndex+1,pageSize,search);
					
					nKeyId = StringProcess.convertToString(nResult.getList().get(0).get(keyFieldName));
					nValue = StringProcess.convertToString(nResult.getList().get(0).get(sortFieldName));
				}
				if(currentPageIndex>0 && currentPageIndex<currentPageCount-1)
				{
					pKeyId=StringProcess.convertToString(list.get(currentPageIndex-1).get(keyFieldName));
					pValue=StringProcess.convertToString(list.get(currentPageIndex-1).get(sortFieldName));
					
					nKeyId=StringProcess.convertToString(list.get(currentPageIndex+1).get(keyFieldName));
					nValue=StringProcess.convertToString(list.get(currentPageIndex+1).get(sortFieldName));
				}
			}
			item.put("PreKeyId", pKeyId);
			item.put("PreValue", pValue);
			item.put("NextKeyId", nKeyId);
			item.put("NextValue", nValue);
		}
		catch(Exception e)
		{
			
		}
		
		return item;
	}

	public static void OnSaveList(Object invokeClass,List<Map<String,Object>> listPageData,List<Map<String,Object>> listData,String keyFieldName,String parentFieldName,String compareFields,boolean allowUpdate)
	{
		try
		{
			for(int i=0;i<listPageData.size();i++)
			{
				Map<String, Object> itemFormTab=listPageData.get(i);
				String keyFieldValue=itemFormTab.get(keyFieldName).toString();
				String parentFieldValue=itemFormTab.get(parentFieldName).toString();
				
				boolean isInsert=false;
				boolean isUpdate=true;
				
				if(keyFieldValue.length()==0)
				{
					keyFieldValue=StringProcess.getUUID();
					isInsert=true;
					isUpdate=false;
				}
				else
				{
					if(listData.size()==0){
						isUpdate=false;
					}
					else
					{
						if(allowUpdate)
						{
							for(int j=0;j<listData.size();j++)
							{
								Map<String, Object> item=listData.get(j);
								if(keyFieldValue.equals(item.get(keyFieldName)))
								{
									String[] compareFieldArray=compareFields.split(",");
									boolean eq=true;
									for(int k=0;k<compareFieldArray.length;k++)
									{
										if(!itemFormTab.get(compareFieldArray[k]).equals(item.get(compareFieldArray[k])))
										{
											eq=false;
											break;
										}
									}
									if(eq)
									{
										isUpdate=false;
										break;
									}
						
								}

							}
						}
						else
						{
							//不做比较
							isUpdate=false;
						}
						
					}

				}
				
				if(isInsert)
				{
					Map<String, Object> model = new HashMap<String, Object>();
					model.put(StringProcess.toLowerCaseFirstOne(keyFieldName), keyFieldValue);
					model.put(StringProcess.toLowerCaseFirstOne(parentFieldName), parentFieldValue);
					String[] compareFieldArray=compareFields.split(",");
					for(int k=0;k<compareFieldArray.length;k++)
					{
						model.put(StringProcess.toLowerCaseFirstOne(compareFieldArray[k]), itemFormTab.get(compareFieldArray[k]));
					}
					//formTabService.insert(model);
					//
					Method m = invokeClass.getClass().getDeclaredMethod("insert", Map.class);
					m.invoke(invokeClass, model);
				}
				else if(isUpdate)
				{
					Map<String, Object> model = new HashMap<String, Object>();
					model.put(StringProcess.toLowerCaseFirstOne(keyFieldName), keyFieldValue);
					model.put(StringProcess.toLowerCaseFirstOne(parentFieldName), parentFieldValue);
					String[] compareFieldArray=compareFields.split(",");
					for(int k=0;k<compareFieldArray.length;k++)
					{
						model.put(StringProcess.toLowerCaseFirstOne(compareFieldArray[k]), itemFormTab.get(compareFieldArray[k]));
					}

					//formTabService.update(model);
					//
					Method m = invokeClass.getClass().getDeclaredMethod("update", Map.class);
					m.invoke(invokeClass, model);
				}
			}
			
			for(int i=0;i<listData.size();i++)
			{
				Map<String, Object> item=listData.get(i);
				String keyFieldValue=StringProcess.convertToString(item.get(keyFieldName));

				boolean isDelete=true;
				
				for(int j=0;j<listPageData.size();j++)
				{
					Map<String, Object> itemFormTab=listPageData.get(j);
					if(keyFieldValue.equals(itemFormTab.get(keyFieldName)))
					{
						isDelete=false;
						break;
					}
				}
				if(isDelete)
				{
					//删除formTabId
					//formTabService.delete(formTabId);
					//
					Method m = invokeClass.getClass().getDeclaredMethod("delete", String.class);
					m.invoke(invokeClass, keyFieldValue);
				}
			}
		}
		catch(Exception e)
		{
			ErrorLog.OnWrite(e);
		}
		
	}
	
	public static void ProcessParams(ModelMap model,List<Map<String, Object>> listFormParams)
	{
		String formParamIds="";
		for(int i=0;i<listFormParams.size();i++)
		{
			Map<String, Object> itemFormParams=listFormParams.get(i);
			
			String paramsId=itemFormParams.get("ParamsId").toString();
			String paramsValueId=StringProcess.convertToString(itemFormParams.get("ParamsValueId"));
			String paramsValue=StringProcess.convertToString(itemFormParams.get("ParamsValue"));
			
			String control="";
			if(itemFormParams.get("ValueType").equals(2))
			{
				String valueCollection=itemFormParams.get("ValueCollection").toString();
				List<Map<String, Object>> listValue=new ArrayList<Map<String, Object>>();
				if(valueCollection.length()>0)
				{
					//dyRowValue2 = StringProcess.decode(dyRowValue2);
					listValue = JSON.parseObject(valueCollection, new TypeReference<List<Map<String,Object>>>(){});
				}
				
				control="<select id=\"c_"+paramsId+"\" name=\"c_"+paramsId+"\" class=\"calcwidth\">";
				control+="<option value=\"\">请选择</option>";
				for(int j=0;j<listValue.size();j++)
				{
					String selectString="";
					if(paramsValue.equals(listValue.get(j).get("Value").toString()))
					{
						selectString=" selected";
					}
					control+="<option value=\""+listValue.get(j).get("Value").toString()+"\""+selectString+">"+listValue.get(j).get("Text").toString()+"</option>";
				}
				control+="</select>";
			}
			else if(itemFormParams.get("ValueType").equals(3))
			{
				control="<select id=\"c_"+paramsId+"\" name=\"c_"+paramsId+"\" class=\"calcwidth\">";
				
				control+="</select>";
			}
			else if(itemFormParams.get("ValueType").equals(4))
			{			
				control+="<textarea id=\"c_"+paramsId+"\" name=\"c_"+paramsId+"\" class=\"calcwidth\" rows=\"6\">"+paramsValue+"</textarea>";
			}
			else
			{
				String readOnly="";
				if("1".equals(itemFormParams.get("ReadOnly")))
				{
					readOnly=" ReadOnly";	
				}
				control="<input type=\"text\" id=\"c_"+paramsId+"\" name=\"c_"+paramsId+"\" value=\""+paramsValue+"\" class=\"calcwidth\""+readOnly+" />";
			}
			control+="<input type=\"hidden\" id=\"cv_"+paramsId+"\" name=\"cv_"+paramsId+"\" value=\""+paramsValueId+"\" />";
			itemFormParams.put("Control", control);
			
			String script="";
			if(itemFormParams.get("IsDepend").equals(1))
			{
				String dependParamsId=itemFormParams.get("DependParamsId").toString();
				String dependParamsValue=itemFormParams.get("DependParamsValue").toString();
				
				script="<script>";
				script+="$(function(){";
				if(paramsValueId.length()==0 && !Arrays.asList(dependParamsValue.split(",")).contains("default"))
				{
					script+="hideElement(\"row_"+paramsId+"\");";
				}
				if(dependParamsValue.length()>0)
				{				
					script+="dependElement(\"row_"+paramsId+"\",\"c_"+dependParamsId+"\",\""+dependParamsValue+"\");";
				}
	
				script+="});";
				script+="</script>";
				
				if(paramsValueId.length()>0)
				{
					formParamIds+=(paramsId+",");
				}
			}
			else
			{
				formParamIds+=(paramsId+",");
			}
			itemFormParams.put("Script", script);
		}
		model.put("listFormParams", listFormParams);
		model.put("formParamIds", formParamIds);
	}
	
}
